<template>
  <div>
  <div ref="container"
       style="width:100%; background-color: #000000;margin:0 auto;position: relative;">
      <video id='webRtcPlayerBox' muted ref="videoPlayer" x5-video-player-type="h5" x5-video-player-fullscreen="true" style="text-align:left;width:100%; position: relative;" autoplay>
        Your browser is too old which doesn't support HTML5 video.
      </video>
    <div class="buttons-box" id="buttonsBox">
      <div class="buttons-box-left">
        <i v-if="!playing" class="iconfont icon-play jessibuca-btn" @click="continuePlay"></i>
        <i v-if="playing" class="iconfont icon-pause jessibuca-btn" @click="pause"></i>
        <i class="iconfont icon-stop jessibuca-btn" @click="destroy"></i>
        <i v-if="isNotMute" class="iconfont icon-audio-high jessibuca-btn" @click="mute()"></i>
        <i v-if="!isNotMute" class="iconfont icon-audio-mute jessibuca-btn" @click="cancelMute()"></i>
      <i v-if="hideptz==='0'"   class="iconfont icon-fangda jessibuca-btn" @mousedown="ptzCamera('zoomin')" @touchstart="ptzCamera('zoomin')" style="font-size: 1rem !important"
          @mouseup="ptzCamera('stop')" @touchend="ptzCamera('stop')"></i>
      <i v-if="hideptz==='0'"   class="iconfont icon-suoxiao jessibuca-btn" @mousedown="ptzCamera('zoomout')" @touchstart="ptzCamera('zoomout')" style="font-size: 1rem !important"
          @mouseup="ptzCamera('stop')" @touchend="ptzCamera('stop')"></i>
      </div>
      <div class="buttons-box-right">
<!--        <span class="jessibuca-btn">{{ kBps }} kb/s</span>-->
        <!--          <i class="iconfont icon-file-record1 jessibuca-btn"></i>-->
        <!--          <i class="iconfont icon-xiangqing2 jessibuca-btn" ></i>-->
<!--        <i class="iconfont icon-camera1196054easyiconnet jessibuca-btn" @click="screenshot"-->
<!--           style="font-size: 1rem !important"></i>-->
        <i class="iconfont icon-shuaxin11 jessibuca-btn" @click="reloadPlay"></i>
        <i v-if="!fullscreen" class="iconfont icon-weibiaoti10 jessibuca-btn" @click="fullscreenSwich"></i>
        <i v-if="fullscreen" class="iconfont icon-weibiaoti11 jessibuca-btn" @click="fullscreenSwich"></i>
      </div>
    </div>
  </div>

    <div class="mobile-ez-ptz-container" id="mobile-ez-ptz-container" v-if="hideptz==='0'"   style="display: inline-block; width: 100%; text-align: center;">
      <div class="live-ptz-title" id="live-ptz-title">云台控制</div>
      <div class="live-ptz-intro" id="live-ptz-intro">请通过操控云台来调整摄像机视角</div>
      <div id="mobile-ez-ptz-item" class="mobile-ez-ptz-wrap"  :style="{'backgroundImage':backgroundImg}">
        <div class="mobile-ez-ptz-container" id="mobile-ez-ptz-container" @mousedown="changePtc($event)" @mouseup="resetPtc" @touchstart="changePtc($event)" @touchend="resetPtc">
          <div class="ez-ptz-main center"></div>
          <div class="mobile-ez-ptz-icon top"  :class="ptz==='top' ? 'active' :'default'" ></div>
          <div class="mobile-ez-ptz-icon left"  :class="ptz==='left' ? 'active' :'default'" ></div>
          <div class="mobile-ez-ptz-icon bottom" :class="ptz==='bottom' ? 'active' :'default'" ></div>
          <div class="mobile-ez-ptz-icon right" :class="ptz==='right' ? 'active' :'default'" ></div>
        </div>
    </div></div>
    <div class="loading" ref="loading" >
      <van-loading type="spinner" color="#1989fa" v-if="loading"  vertical>加载中...</van-loading>
  </div>
  </div>
</template>

<script>
import {Notify} from "vant";
let webrtcPlayer = null;
export default {
  name: 'h5player',
  data() {
    return {
      playing: false,
      isNotMute: false,
      fullscreen:false,
      loaded: false, // mute
      speed: 0,
      performance: "", // 工作情况
      kBps: 0,
      volume: 1,
      rotate: 0,
      vod: true, // 点播
      forceNoOffscreen: false,
      controSpeed:76,
      zoomSpeed:4,
      deviceId:'',
      channelId:"",
      ptz:'',
      backgroundImg:'',
      videoUrl:'',
      timer: null,
      screenshotData: null,
      loading:false,
      hideptz:"0"
    };
  },
  created() {
  },
  mounted(){
    let url = decodeURIComponent(this.$route.params.url);
    let name = this.$route.query.name || '国标28181';
    this.hideptz = this.$route.query.hideptz || "0";
    this.$nextTick(() => {
      console.log(2222)
      document.title = name
      this.updatePlayerDomSize()
      window.onresize = this.updatePlayerDomSize
      this.videoUrl = url;
      var params = this.getUrlParams(url).stream.split('_');
      this.deviceId = params[0];
      this.channelId = params[1];
      this.playVideo(url)
    })

  },
  methods: {
    getUrlParams(url) {
      // 如果浏览器支持URLSearchParams
      if (typeof URLSearchParams!== 'undefined') {
        let searchParams = new URLSearchParams(new URL(url).search);
        let params = {};
        for (let [key, value] of searchParams.entries()) {
          params[key] = value;
        }
        return params;
      } else {
        // 手动解析
        let queryString = url.split('?')[1];
        if (!queryString) {
          return {};
        }
        let paramsArray = queryString.split('&');
        let params = {};
        for (let i = 0; i < paramsArray.length; i++) {
          let param = paramsArray[i].split('=');
          params[param[0]] = param[1];
        }
        return params;
      }
    },
    eventcallbacK: function(type, message) {
      console.log("player 事件回调")
      console.log(type)
      console.log(message)
    },
    isWeChat(){
      //window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息，这个属性可以用来判断浏览器类型
      var ua = window.navigator.userAgent.toLowerCase();
      //通过正则表达式匹配ua中是否含有MicroMessenger字符串
      if(ua.match(/MicroMessenger/i) == 'micromessenger'){
        return true;
      }else{
        return false;
      }
    },
    changePtc(e){
      var container = document.getElementById('mobile-ez-ptz-item').getBoundingClientRect();
      var containerCenterX = container.left + 130;
      var containerCenterY = container.top + 130;
      var eventX = e.x || e.changedTouches[0].clientX;
      var eventY = e.y || e.changedTouches[0].clientY;
      var left = eventX - containerCenterX;
      var top = eventY - containerCenterY;
      // 判读方位
      if (Math.abs(left) > Math.abs(top)) {
        if (left > 0) {
          this.ptz = "right";
          this.backgroundImg = 'linear-gradient(270deg, rgb(192, 221, 241) 0%, rgba(100, 143, 252, 0) 50%)';
        } else {
          this.ptz = "left";
          this.backgroundImg = 'linear-gradient(90deg, rgb(192, 221, 241) 0%, rgba(100, 143, 252, 0) 50%)';
        }
      } else {
        if (top > 0) {
          this.ptz = "down";
          this.backgroundImg = 'linear-gradient(0deg, rgb(192, 221, 241) 0%, rgba(100, 143, 252, 0) 50%)';
        } else {
          this.ptz = "up";
          this.backgroundImg = 'linear-gradient(rgb(192, 221, 241) 0%, rgba(100, 143, 252, 0) 50%)';
        }
      }
      this.$nextTick(() => {
        this.ptzCamera(this.ptz)
      })
    },
    resetPtc(){
      this.ptz = '';
      this.backgroundImg = '';
      this.ptzCamera('stop')
    },
    updatePlayerDomSize() {
      let dom = this.$refs.container;
      let videodom = this.$refs.videoPlayer;
      let loading = this.$refs.loading;
      let width = dom.parentNode.clientWidth
      let height = (9 / 16) * width
      console.log(height)

      if (width > 0 && height > 0) {
        dom.style.width = width + 'px';
        dom.style.height = height + "px";
        dom.style.paddingTop = 0;
        videodom.style.width = width + 'px';
        videodom.style.height = height + 'px';
        loading.style.height = height + 'px';
        console.log(width)
        console.log(height)
      }
    },
    ptzCamera: function (command) {
      console.log('云台控制：' + command);
      let that = this;
      this.$axios({
        method: 'get',
        url: '/api/front-end/ptz/' + this.deviceId + '/' + this.channelId + '?command=' + command + '&horizonSpeed=' + this.controSpeed + '&verticalSpeed=' + this.controSpeed + '&zoomSpeed=' + this.zoomSpeed,
      }).then(function (res) {
      });
    },
    reloadPlay: function () {
      this.destroy().then(() => {
        this.playVideo(this.videoUrl)
      })
    },
    playVideo: function (url) {
      if(!url){
        return
      }
      this.loading = true;
      console.log('webrtc播放地址：',url)
      webrtcPlayer = new ZLMRTCClient.Endpoint({
        element: document.getElementById('webRtcPlayerBox'),// video 标签
        debug: false,// 是否打印日志
        zlmsdpUrl: url,//流地址
        simulecast: false,
        useCamera: false,
        audioEnable: true,
        videoEnable: true,
        recvOnly: true,
        usedatachannel: false,
      })
      webrtcPlayer.on(ZLMRTCClient.Events.WEBRTC_ICE_CANDIDATE_ERROR,(e)=>{// ICE 协商出错
        console.error('ICE 协商出错')
        this.loading = false;
        Notify({ type: 'danger', message: 'ICE协商出错，请联系管理员' });
        this.eventcallbacK("ICE ERROR", "ICE 协商出错")
      });

      webrtcPlayer.on(ZLMRTCClient.Events.WEBRTC_ON_REMOTE_STREAMS,(e)=>{//获取到了远端流，可以播放
        console.log('播放成功',e.streams)
        this.loading = false;
        this.playing = true;
        this.loaded = true;
        this.eventcallbacK("playing", "播放成功")
      });

      webrtcPlayer.on(ZLMRTCClient.Events.WEBRTC_OFFER_ANWSER_EXCHANGE_FAILED,(e)=>{// offer anwser 交换失败
        console.error('offer anwser 交换失败',e)
        this.loading = false;
        Notify({ type: 'danger', message: 'offer anwser 交换失败，请联系管理员' });
        this.eventcallbacK("OFFER ANSWER ERROR ", "offer anwser 交换失败")
        if (e.code ==-400 && e.msg=="流不存在"){
          console.log("流不存在")
          this.timer = setTimeout(()=>{
            this.webrtcPlayer.close();
            this.play(url)
          }, 100)

        }
      });
      webrtcPlayer.on(ZLMRTCClient.Events.WEBRTC_ON_LOCAL_STREAM,(s)=>{// 获取到了本地流
        // document.getElementById('selfVideo').srcObject=s;
        this.eventcallbacK("LOCAL STREAM", "获取到了本地流")
      });
    },
    pause: function () {
      if (webrtcPlayer != null) {
        webrtcPlayer.close();
        webrtcPlayer = null;
      }
      this.playing = false;
      this.err = "";
      this.performance = "";
    },
    continuePlay: function () {
      this.playVideo(this.videoUrl)
    },
    // 截屏功能（这里只是简单示例，实际可能需要处理跨域等问题）
    screenshot() {
      const videoPlayer = this.$refs.videoPlayer;
      const canvas = document.createElement('canvas');
      canvas.width = videoPlayer.videoWidth;
      canvas.height = videoPlayer.videoHeight;
      const ctx = canvas.getContext('2d');
      ctx.drawImage(videoPlayer, 0, 0, canvas.width, canvas.height);
      this.screenshotData = canvas.toDataURL('image/png');
      this.downloadScreenshot()
    },
    // 下载截屏
    downloadScreenshot() {
      if (this.screenshotData) {
        const link = document.createElement('a');
        link.href = this.screenshotData;
        link.download = 'screenshot.png';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      } else {
        console.log('请先进行截屏操作');
      }
    },
    mute: function () {
      this.$refs.videoPlayer.muted = true;
      this.isNotMute = false;
    },
    cancelMute: function () {
      this.$refs.videoPlayer.muted = false;
      this.isNotMute = true;
    },
    destroy: function () {
      clearTimeout(this.timer);
      if (webrtcPlayer != null) {
        webrtcPlayer.close();
      }
      webrtcPlayer = null;
      this.playing = false;
      this.loaded = false;
      this.err = "";
      this.performance = "";
      return this.$axios({
        method: 'get',
        url: '/api/play/stop/' + this.deviceId + '/' + this.channelId
      })
    },
    fullscreenSwich: function () {
      this.toggleFullscreen();
    },
    // 切换全屏
    toggleFullscreen() {
      const videoPlayer = this.$refs.videoPlayer;
      if (!document.fullscreenElement) {
        if (videoPlayer.requestFullscreen) {
          videoPlayer.requestFullscreen();
        } else if (videoPlayer.webkitRequestFullscreen) {
          videoPlayer.webkitRequestFullscreen();
        } else if (videoPlayer.msRequestFullscreen) {
          videoPlayer.msRequestFullscreen();
        }
      } else {
        if (document.exitFullscreen) {
          document.exitFullscreen();
        } else if (document.webkitExitFullscreen) {
          document.webkitExitFullscreen();
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen();
        }
      }
      this.isNotMute = !videoPlayer.muted;
    },
  },
  beforeDestroy() {
    this.destroy()
  },
}
</script>

<style>
.buttons-box {
  width: 100%;
  height: 28px;
  background-color: rgba(43, 51, 63, 0.7);
  position: absolute;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  left: 0;
  bottom: 0;
  user-select: none;
  z-index: 10;
}

.jessibuca-btn {
  width: 20px;
  color: rgb(255, 255, 255);
  line-height: 27px;
  margin: 0px 10px;
  padding: 0px 2px;
  cursor: pointer;
  text-align: center;
  font-size: 0.8rem !important;
}

.buttons-box-right {
  position: absolute;
  right: 0;
}

#mobile-ez-ptz-container {
  display: inline-block;
  width: 375px;
  text-align: center;
}
.live-ptz-title{
  height: 25px;
  font-size: 18px;
  color: #2c2c2c;
  text-align: center;
  font-weight: 700;
  margin: 24px 0 12px;
}
.live-ptz-intro {
  margin-bottom: 24px;
  color: #aaaaaa;
}
.mobile-ez-ptz-wrap {
  background-image: linear-gradient(180deg, #f6f8ff 0%, #ededed6b 50%)
}
#mobile-ez-ptz-container .mobile-ez-ptz-container {
  position: relative;
  width: 260px;
  height: 260px;
  background: rgba(255, 255, 255, 0.80);
  border: 1px solid rgba(255, 255, 255, 0.80);
  border-radius: 100%;
  overflow: hidden;
  margin: auto;
}

#mobile-ez-ptz-container .mobile-ez-ptz-container .mobile-ez-ptz-icon.top {
  width: 0;
  height: 0;
  border-left: 6px solid transparent;
  border-right: 6px solid transparent;
  border-bottom: 6px solid #aaaaaa;
  position: absolute;
  display: inline-block;
  left: calc(50% - 6px);
  top: 10px;
}

#mobile-ez-ptz-container .mobile-ez-ptz-container .mobile-ez-ptz-icon.top.active {
  border-bottom-color: #1890FF;
}

#mobile-ez-ptz-container .mobile-ez-ptz-container .mobile-ez-ptz-icon.bottom {
  width: 0;
  height: 0;
  border-left: 6px solid transparent;
  border-right: 6px solid transparent;
  border-top: 6px solid #aaaaaa;
  position: absolute;
  display: inline-block;
  left: calc(50% - 6px);
  bottom: 10px;
}

#mobile-ez-ptz-container .mobile-ez-ptz-container .mobile-ez-ptz-icon.bottom.active {
  border-top-color: #1890FF;

}

#mobile-ez-ptz-container .mobile-ez-ptz-container .mobile-ez-ptz-icon.right {
  width: 0;
  height: 0;
  border-top: 6px solid transparent;
  border-bottom: 6px solid transparent;
  border-left: 6px solid #aaaaaa;
  position: absolute;
  display: inline-block;
  top: calc(50% - 6px);
  right: 10px;
}

#mobile-ez-ptz-container .mobile-ez-ptz-container .mobile-ez-ptz-icon.right.active {
  border-left-color: #1890FF;

}

#mobile-ez-ptz-container .mobile-ez-ptz-container .mobile-ez-ptz-icon.left {
  width: 0;
  height: 0;
  border-top: 6px solid transparent;
  border-bottom: 6px solid transparent;
  border-right: 6px solid #aaaaaa;
  position: absolute;
  display: inline-block;
  top: calc(50% - 6px);
  left: 10px;
}

#mobile-ez-ptz-container .mobile-ez-ptz-container .mobile-ez-ptz-icon.left.active {
  border-right-color: #1890FF;

}

#mobile-ez-ptz-container .mobile-ez-ptz-container .ez-ptz-main.center {
  width: 52px;
  height: 52px;
  background: #FFFFFF;
  border: 2px solid #eee;
  border-radius: 100%;
  top: calc(50% - 26px);
  left: calc(50% - 26px);
  position: absolute;
  /* box-shadow: 0px -39px 40px 6px #1890ff; */
}

#mobile-ez-ptz-container .mobile-ez-ptz-wrap {
  display: inline-block;
  padding: 24px 24px;
  border-radius: 100%;
  overflow: hidden;
}

#mobile-ez-ptz-container .ez-ptz-close {
  position: absolute;
  color: #FFFFFF;
  top: 0;
  right: 0px;
}
html,body{
    padding: 0;
    margin: 0;
    text-align: center;
    background: #FFFFFF;
    overflow: hidden;
}
#app{
  background: #FFFFFF;
}
video::-webkit-media-controls-timeline {
  display: none;
}
.loading {
  position: absolute;
  width: 100%;
  height: 200px;
  top:0;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
